package com.zlzlib.librxoknet.function;



import com.zlzlib.librx.ProgressInfo;
import com.zlzlib.librx.listener.ProgressListener;
import com.zlzlib.librxoknet.util.RxUtil;

import java.io.File;

import io.reactivex.rxjava3.functions.Function;
import okhttp3.ResponseBody;

/**
 * Created by zlz on 2019/8/15.
 */
public class FileFunction implements Function<ResponseBody, File> {

    private final ProgressListener listener;
    /**
     * 目标文件存储的文件夹路径
     */
    private final String destFileDir;
    /**
     * 目标文件存储的文件名
     */
    private final String destFileName;
    //是否断点续传
    private boolean isAppendFile = false;

    public FileFunction(ProgressListener listener, String destFileDir, String destFileName) {
        this.listener = listener;
        this.destFileDir = destFileDir;
        this.destFileName = destFileName;
    }

    public FileFunction(ProgressListener listener, String destFileDir, String destFileName, boolean isAppendFile) {
        this.listener = listener;
        this.destFileDir = destFileDir;
        this.destFileName = destFileName;
        this.isAppendFile = isAppendFile;
    }

    @Override
    public File apply(ResponseBody s) throws Exception {
        ProgressInfo info = new ProgressInfo(System.currentTimeMillis());
        info.setMsg("saving...");
        info.setContentLength(s.contentLength());
        File file = RxUtil.saveFile(s.byteStream(), info, listener, destFileDir, destFileName, isAppendFile);
        s.close();
        return file;
    }

    public void setAppendFile(boolean appendFile) {
        isAppendFile = appendFile;
    }
}